#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    long long maximumSubarraySum(vector<int>& nums, int k) {
        unordered_map<int, vector<int>> hash;
        int n = nums.size();
        vector<long long> dp(n + 1);

        for (int i = 0; i < n; ++i)
        {
            hash[nums[i]].push_back(i);
            dp[i + 1] = dp[i] + nums[i];
        }

        long long ret = LLONG_MIN;
        set<int> check;
        for (int i = 0; i < n - 1; ++i)
        {
            int f1 = nums[i] - k;
            int f2 = nums[i] + k;
            if (hash.count(f1))
            {
                for (auto& e : hash[f1])
                {
                    if (e <= i)
                        continue;
                    ret = max((dp[e + 1] - dp[i]), ret);
                }
            }
            if (hash.count(f2))
            {
                for (auto& e : hash[f2])
                {
                    if (e <= i)
                        continue;
                    ret = max((dp[e + 1] - dp[i]), ret);
                }
            }
        }

        return ret == LLONG_MIN ? 0 : ret;
    }
};